<style src="@wangeditor/editor/dist/css/style.css">

</style>
<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.courseId ? $t('add') : $t('update')"
    :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
      :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-form-item label="类型" prop="courseType">
        <el-radio-group v-model="dataForm.courseType">
          <el-radio  :label="0" @click.native="isCourseType('0')">约课</el-radio>
          <el-radio  :label="1" @click.native="isCourseType('1')">场馆</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分类" prop="courseCategory">
        <template>
          <el-select v-model="dataForm.courseCategory" placeholder="请选择">
            <el-option v-for="item in typeList" :key="item.dictLabel" :label="item.dictLabel" :value="item.dictLabel">
            </el-option>
          </el-select>
        </template>
      </el-form-item>

      <el-form-item label="商家名" prop="courseName">
        <el-input v-model="dataForm.courseName" placeholder="商家名"></el-input>
      </el-form-item>

      <el-form-item label="课程名" prop="curriculum">
        <el-input v-model="dataForm.curriculum" placeholder="课程名"></el-input>
      </el-form-item>

      <el-form-item label="课程价格" prop="curriculumPrice">
        <el-input v-model="dataForm.curriculumPrice" type='number' placeholder="课程价格"></el-input>
      </el-form-item>

      <el-form-item label="主页图片" prop="configureUrl">
        <el-upload :action="action" list-type="picture-card" ref="upload" :limit="1" :on-success="uploadSuccess"
          :on-remove="handleRemove" :on-preview="handlePictureCardPreview">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>

      <el-form-item label="内容介绍" prop="courseContent">
        <template>
          <div style="border: 1px solid #ccc;">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="dataForm.courseContent"
              :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
          </div>
        </template>
        <!-- <el-input v-model="dataForm.courseContent" placeholder="课程商家"></el-input> -->

      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item label="商家电话" prop="coursePhone">
        <el-input v-model="dataForm.coursePhone" placeholder="商家电话"></el-input>
      </el-form-item>
      <el-form-item label="商家地址" prop="courseAddress">
        <el-input v-model="dataForm.courseAddress" placeholder="商家地址"></el-input>
      </el-form-item>

    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import Cookies from 'js-cookie'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IEditorConfig } from '@wangeditor/editor'
export default {
  components: { Editor, Toolbar },
  data() {
    return {
      visible: false,
      radio: 0,
      action: '',
      dataForm: {
        courseId: '',
        courseType: 0,
        courseCategory: '',
        courseContent: '',
        courseName: '',
        status: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: '',
        configureUrl: '',
        remark: '',
        coursePhone: '',
        courseAddress: '',
        curriculum: '',
        curriculumPrice: 0.00,
      },
      editor: null,
      html: '<p>hello</p>',
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default',
      placeTypeList: [],
      courseTypeList: [],
      typeList: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    dataRule() {
      return {
        courseType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        courseCategory: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        courseContent: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        courseName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        createBy: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        updateBy: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        updateTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        configureUrl: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        remark: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        coursePhone: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        courseAddress: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        curriculum: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        curriculumPrice: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // this.editor
    // 创建编辑器
    // const editor = Editor({
    //   selector: '#editor-container'
    // })
    // // 创建工具栏
    // const toolbar = Editor({
    //   editor,
    //   selector: '#toolbar-container'
    // })
  },
  methods: {
    init() {
      this.action = `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${Cookies.get('token')}`
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.courseId) {
          this.getInfo()
        }
      }),
        this.$http.get(`/sys/dict/type/all`
        ).then(({ data: res }) => {
          console.log(res.data)

          for (let item of res.data) {
            if (item.dictType == 'place_type') {
              this.placeTypeList = item.dataList;
            }

            if (item.dictType == 'course_type') {
              this.courseTypeList = item.dataList;
            }
          }
          this.typeList = this.courseTypeList;

        }).catch(() => { })


      const editor = this.editor // 获取 editor 实例
      if (editor == null) return

    },
    // 获取信息
    getInfo() {
      this.$http.get(`/we/wecoursedata/${this.dataForm.courseId}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => { })
    },
    isCourseType(type) {
      if (type == 0) {
        this.typeList = this.courseTypeList;
      } else {
        this.typeList = this.placeTypeList;
      }
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      var xss = require('xss');
      console.log(xss(this.dataForm.courseContent))
      this.dataForm.courseContent = xss(this.dataForm.courseContent)
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.courseId ? 'post' : 'put']('/we/wecoursedata/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错

    },
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy() // 组件销毁时，及时销毁编辑器
    },
    handleRemove(file, fileList) {
      this.dataForm.configureUrl = '';
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    uploadSuccess(response, file, fileList) {
      this.dataForm.configureUrl = response.data.src;
      console.log(response)
    }
  }
}
</script>
